package com.ruoyi.system.service.impl;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.StuCertificateMapper;
import com.ruoyi.system.mapper.StuDataCerStateMapper;
import com.ruoyi.system.mapper.StuDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.StuDataCerMapper;
import com.ruoyi.system.service.IStuDataCerService;
import com.ruoyi.common.core.text.Convert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder.log;

/**
 * 学生信息和证书关联表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-11
 */
@Service
public class StuDataCerServiceImpl implements IStuDataCerService 
{
    @Autowired
    private StuDataCerMapper stuDataCerMapper;
    @Autowired
    private StuDataCerStateMapper stuDataCerStateMapper;
    @Autowired
    private StuDataMapper stuDataMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private StuCertificateMapper stuCertificateMapper;

    /**
     * 查询学生信息和证书关联表
     * 
     * @param studataCerId 学生信息和证书关联表主键
     * @return 学生信息和证书关联表
     */
    @Override
    public StuDataCer selectStuDataCerByStudataCerId(Long studataCerId)
    {
        return stuDataCerMapper.selectStuDataCerByStudataCerId(studataCerId);
    }

    /**
     * 查询学生信息和证书关联表列表
     * 
     * @param stuDataCer 学生信息和证书关联表
     * @return 学生信息和证书关联表
     */
    @Override
    @DataScope(userAlias = "u",deptAlias = "u")
    public List<StuDataCer> selectStuDataCerList(StuDataCer stuDataCer)
    {
        return stuDataCerMapper.selectStuDataCerList(stuDataCer);
    }

    /**
     * 新增学生信息和证书关联表
     * 
     * @param stuDataCer 学生信息和证书关联表
     * @return 结果
     */
    @Override
    public int insertStuDataCer(StuDataCer stuDataCer)
    {
        return stuDataCerMapper.insertStuDataCer(stuDataCer);
    }

    /**
     * 修改学生信息和证书关联表
     * 
     * @param stuDataCer 学生信息和证书关联表
     * @return 结果
     */
    @Override
    public int updateStuDataCer(StuDataCer stuDataCer)
    {
        return stuDataCerMapper.updateStuDataCer(stuDataCer);
    }

    /**
     * 批量删除学生信息和证书关联表
     * 
     * @param studataCerIds 需要删除的学生信息和证书关联表主键
     * @return 结果
     */
    @Override
    public int deleteStuDataCerByStudataCerIds(String studataCerIds)
    {
        return stuDataCerMapper.deleteStuDataCerByStudataCerIds(Convert.toStrArray(studataCerIds));
    }

    @Override
    public int deleteStuDataCerByStuIds(String stuIds) {
        return stuDataCerMapper.deleteStuDataCerByStuIds(Convert.toStrArray(stuIds));
    }

    @Override
    public int deleteStuDataCerByCerIds(String cerIds) {
        return stuDataCerMapper.deleteStuDataCerByCerIds(Convert.toStrArray(cerIds));
    }
    /**
     * 删除学生信息和证书关联表信息
     * 
     * @param studataCerId 学生信息和证书关联表主键
     * @return 结果
     */
    @Override
    public int deleteStuDataCerByStudataCerId(Long studataCerId)
    {
        return stuDataCerMapper.deleteStuDataCerByStudataCerId(studataCerId);
    }

    @Override
    public int changeIspublic(StuDataCer stuDataCer) {
        return stuDataCerMapper.updateStuDataCer(stuDataCer);
    }

    @Override
    public int reviewByStudataCerIds(String ids) {
        return stuDataCerMapper.reviewByStudataCerIds(Convert.toStrArray(ids));
    }

    @Override
    public void downloadFiles(String studataCerIds, HttpServletRequest request, HttpServletResponse response) {
        // 以逗号分割字符串，输出成数组
        String[] array = Convert.toStrArray(studataCerIds);
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();;
        StuDataCer stuDataCer;
        //获取文件路径
        String filePaths;
        //文件后缀
        String fileExtend;
        //文件显示名称
        String nameShow;
        List<Map> fileList = new ArrayList();
        for (int i = 0; i < array.length; i++)
        {
            HashMap map = new HashMap();
            stuDataCer = stuDataCerMapper.selectStuDataCerByStudataCerId(Convert.toLong(array[i]));

            filePaths = localPath + StringUtils.substringAfter(stuDataCer.getFilePath(), Constants.RESOURCE_PREFIX);

            fileExtend = StringUtils.substringAfterLast(filePaths, ".");

            nameShow = stuDataCer.getCerName() + "_" + stuDataCer.getStuNumber() + "_" + stuDataCer.getStuName() + "_" + array[i] + "." + fileExtend;
            //设置参数

            map.put("nameShow", nameShow);
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                //创建文件输入流
                FileInputStream fis = new FileInputStream(filePaths);
                BufferedInputStream bis = new BufferedInputStream(fis);
                //字节输出流，注意要全部读取完成才能进行下一步
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int c = bis.read();//读取bis流中的下一个字节
                while (c != -1) {
                    baos.write(c);
                    c = bis.read();
                }
                bis.close();
                byte retArr[] = baos.toByteArray();
                map.put("outByte", retArr);
                fileList.add(map);
                bis.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        zipFiles(fileList,response);
    }

    //多个文件压缩成压缩包并下载
    public void zipFiles(List<Map> fileList, HttpServletResponse httpResponse) {

        try(ZipOutputStream zipOutputStream = new ZipOutputStream(httpResponse.getOutputStream()); OutputStream out =null) {
            //下载压缩包
            httpResponse.setContentType("application/zip");
            httpResponse.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("随便.zip", "UTF-8"));
            // 创建 ZipEntry 对象
            for (Map map:fileList){
                ZipEntry zipEntry =  new ZipEntry((String) map.get("nameShow"));
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write((byte[]) map.get("outByte"));
            }
        } catch (IOException e) {
            //日志输出
            log.error(e.getMessage(), e);
        }
    }
    @Override
    public int insertStuDataCerState(StuDataCerState stuDataCerState) {
        StuDataCer stuDataCer = new StuDataCer();
        stuDataCer.setStudataCerId(stuDataCerState.getStudataCerId());
        stuDataCer.setReviewStatus(stuDataCerState.getReviewStatus());
        stuDataCerMapper.updateStuDataCer(stuDataCer);
        if(Objects.equals(stuDataCerState.getIsEmail(), "on")){
            send(stuDataCerState);
        }
        return stuDataCerStateMapper.insertStuDataCerState(stuDataCerState);
    }

    public void send(StuDataCerState stuDataCerState){
        try{
        //发送邮箱
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        StuDataCer stuDataCer = stuDataCerMapper.selectStuDataCerByStudataCerIdNew(stuDataCerState.getStudataCerId());
        //设置发送人
        mailMessage.setFrom(EmailConfig.getEmail());
        //邮件主题
        mailMessage.setSubject(stuDataCer.getStuNumber()+"_"+stuDataCer.getStuName()+"关于你的《"+stuDataCer.getCerName()+"》证书审核状态更新了");
        //邮件内容
        mailMessage.setText("审核状态: "+checkReviewStatus(stuDataCer.getReviewStatus())
                +"\n\n审核原因: "+stuDataCerState.getReviewInfo()+
                "\n\n审核人: "+stuDataCerState.getReviewBy()+
                "\n\n审核时间: "+stuDataCerState.getReviewTime());
        //收件人
        mailMessage.setTo(stuDataCer.getEmail());
        javaMailSender.send(mailMessage);
        } catch(Exception e) {
            log.error("邮箱报错！！"+e.getMessage(), e);
            System.out.println("邮件发送失败！！！");
        }
    }
    public String checkReviewStatus(String value) {
        Long reviewStatus = Convert.toLong(value);
        if(reviewStatus == 0){return "未审核";}
        else if(reviewStatus == 1){return "审核中";}
        else if(reviewStatus == 2){return "审核通过";}
        else if(reviewStatus == 3){return "审核未通过";}
        return value;
    }

    @Override
    public ArrayList<Echarts> reviewStataCount(StuDataCer stuDataCer) {
        return stuDataCerMapper.reviewStataCount(stuDataCer);
    }
}
